import store from '../_redux/store'
import { message } from 'antd'

/**
 * post请求构造
 * @param body
 * @param flag
 * @returns {Object}
 */
export const postInit = (body, flag = true) => ({
  method: 'POST',
  body: JSON.stringify(body),
  headers: headers(flag),
  mode: 'cors'
})

/**
 * 构造带有AccessToken 的headers
 * @returns {{accesstoken: string, 'content-type': string}}
 */
export const headers = (flag) => {
  let _headers = {
    'accesstoken': '',
    'content-type': 'application/json'
  }
  let { accessToken } = flag ? store.getState().$UserState : store.getState().$AdminPageState
  if (accessToken !== '') {
    _headers['accesstoken'] = accessToken
  }
  return _headers
}

/**
 * get请求构造
 * @returns {{mode: string, headers: Headers}}
 */
export const getInit = (flag = true) => ({
  headers: headers(flag),
  mode: 'cors'
})

/**
 * put 请求构造
 * @param body
 * @param flag
 * @returns {{mode: string, headers: {accesstoken: string, 'content-type': string}, method: string, body: string}}
 */
export const putInit = (body, flag = true) => ({
  headers: headers(flag),
  mode: 'cors',
  method: 'PUT',
  body: JSON.stringify(body),
})

/**
 * delete 请求构造
 * @param body
 * @param flag
 * @returns {{mode: string, headers: {accesstoken: string, 'content-type': string}, method: string, body: string}}
 */
export const deleteInit = (body, flag = true) => ({
  method: 'DELETE',
  body: JSON.stringify(body),
  headers: headers(flag),
  mode: 'cors',
})

/**
 * 生成url query字符串, 不带问号，需自行添加问号
 * @param {Object} args query参数列表，args为一个object
 * @returns {string}
 */
export const query = (args = {}) => {
  let result = ''
  args.userId = args.userId || store.getState().$UserState.userId
  for (const key in args) if (args.hasOwnProperty(key)) {
    const value = args[key]
    if (result.length !== 0) result += '&'
    result += key + '=' + value
  }
  return result
}

/**
 *
 * @param {string} url
 * @param {Object} init 初始化对象
 * @returns {Promise<JSON>}
 */
export const request = async (url, init = {}) => {
  const response = await fetch(url, init)
  if (response.status === 200) {
    return response.json()
  } else if (response.status >= 400 && response.status < 500) {
    error('请求错误')
    return Promise.reject('请求错误')
  } else if (response.status >= 500) {
    error('服务器错误')
    return Promise.reject('服务器错误')
  } else {
    error('未知错误')
    return Promise.reject('未知错误')
  }
}

/**
 * 成功toast 提示
 * @param msg
 */
export const success = msg => {
  message.success(msg)
}

/**
 * 错误 toast 提示
 * @param msg
 */
export const error = msg => {
  message.error(msg)
}

/**
 * 警告 toast 提示
 * @param msg
 */
export const warning = msg => {
  message.warning(msg)
}